package utd.cs6322.cluster.visualization;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.ListIterator;

import net.sf.javaml.core.Dataset;
import net.sf.javaml.core.Instance;

import prefuse.data.Graph;
import prefuse.data.Node;
import prefuse.data.Tree;
import prefuse.data.io.DataIOException;
import prefuse.data.io.GraphMLReader;
import prefuse.data.io.GraphMLWriter;
import utd.cs6322.cluster.document.Document;

public class TreeBuilder {
	
	private Graph tree = null;
	private Node root;
	
	public TreeBuilder() {
		tree = new Graph();
		root = tree.addNode();
		tree.addColumn("maxclass", String.class);
		tree.addColumn("docids", String[].class);
		tree.addColumn("numdocs", Integer.class);
	}
	
	public Graph getTree(){
		return tree;
	}
	
	public void writeTree(File file) throws FileNotFoundException, DataIOException{
		GraphMLWriter writer = new GraphMLWriter();
		writer.writeGraph(tree, new FileOutputStream(file));
	}
	
	public void readTree(File file) throws DataIOException{
		GraphMLReader reader = new GraphMLReader();
		tree = reader.readGraph(file);
	}
	
	public Node setRootDocs(Dataset set){
		return setUpNode(root, null, set);
	}
	
	public Node addCluster(Node parent, Dataset set){
		return setUpNode(tree.addNode(), parent, set);
	}
	
	public Node addCluster(Dataset set){
		return setUpNode(tree.addNode(), root, set);
	}
	
	private Node setUpNode(Node node, Node parent, Dataset set){
		if(parent != null)
			tree.addEdge(parent, node); 
		HashMap<String, Integer> count = new HashMap<String, Integer>();
		Iterator<Instance> iter = set.iterator();
		while(iter.hasNext()){
			Instance inst = iter.next();
			String classVal = (String)inst.classValue();
			if(count.containsKey(classVal))
				count.put(classVal, count.get(classVal) + 1);
			else
				count.put(classVal, 1);
		}
		String maxClass = "";
		int maxNum = 0;
		for(String key : count.keySet())
			if(count.get(key) > maxNum){
				maxClass = key;
				maxNum = count.get(key);
			}

		node.set("maxclass", maxClass);
		
		node.set("numdocs", set.size());
		return node;
	}
	 
}
